package cn.zurish.cloud.kafka.mysql.toolikt;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

public class IDGenerator {
    private static final String PREFIX = "BQ";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final int MAX_SEQUENCE = 9999;
    private static AtomicInteger sequence = new AtomicInteger(1000);
    private static String currentDate = LocalDate.now().format(DATE_FORMATTER);

    public static synchronized String generateId() {
        LocalDate now = LocalDate.now();
        String today = now.format(DATE_FORMATTER);

        // 如果日期变更，重置序列号
        if (!today.equals(currentDate)) {
            currentDate = today;
            sequence.set(0);
        }

        // 获取当前序列号并递增
        int current = sequence.getAndIncrement();

        // 处理序列号溢出
        if (current > MAX_SEQUENCE) {
            throw new IllegalStateException("序列号已达到最大值");
        }

        // 格式化为4位数字，不足补零
        String formattedSequence = String.format("%04d", current);

        return PREFIX + today + formattedSequence;
    }

    public static void main(String[] args) {
        // 测试生成10个ID
        for (int i = 0; i < 10; i++) {
            System.out.println(generateId());
        }
    }
}
